import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';

import { IMyDpOptions, IMyDateModel } from 'mydatepicker';

@Component({
  selector: 'app-date',
  templateUrl: './date.component.html',
  styleUrls: ['./date.component.css']
})
export class DateComponent implements OnInit {

  @Input() dataModel = { formatted: '' };

  @Input() placeholder = '';

  @Input() width = '100%';
  @Input() height = '34px';
  @Input() dateFormat = 'yyyy-mm-dd';

  dayLabels = { su: '日', mo: '一', tu: '二', we: '三', th: '四', fr: '五', sa: '六' };
  monthLabels = {
    1: '一月', 2: '二月', 3: '三月', 4: '四月', 5: '五月', 6: '六月',
    7: '七月', 8: '八月', 9: '九月', 10: '十月', 11: '十一月', 12: '十二月'
  };
  todayBtnTxt = '今天';

  public myForm: FormGroup;

  public dateOpts: IMyDpOptions;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.dateOpts = {
      dateFormat: this.dateFormat,
      dayLabels: this.dayLabels,
      monthLabels: this.monthLabels,
      showTodayBtn: true,
      todayBtnTxt: this.todayBtnTxt,
      firstDayOfWeek: 'su',
      showIncreaseDateBtn: false,
      inline: false,
      width: this.width,
      height: this.height,
    };
    this.myForm = this.formBuilder.group({
      myDate: [null, Validators.required]
    });
  }

  onDateChanged(event: IMyDateModel) {
    this.dataModel.formatted = event.formatted;
  }

  setDate(): void {
    if (!this.dataModel || !this.dataModel.formatted) {
      return;
    }
    let arr = this.dataModel.formatted.split('-');
    this.myForm.patchValue({
      myDate: {
        date: {
          year: parseInt(arr[0], 10),
          month: parseInt(arr[1], 10),
          day: parseInt(arr[2], 10)
        }
      }
    });
  }

  clearDate() {
    this.myForm.patchValue({ myDate: null });
  }

}
